﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Drawing.Drawing2D;

using LTJ.Common;
using LTJ.Config;
using LTJ.Entity;
using LTJ.Data;

namespace LTJ.FrameWork
{
    /// <summary>
    /// 工具
    /// </summary>
    public class FrameWorkUtil
    {
        /// <summary>
        /// 验证码生成的取值范围
        /// </summary>
        private static string[] verifycodeRange = { "1","2","3","4","5","6","7","8","9",
                                                    "a","b","c","d","e","f","g",
                                                    "h",    "j","k",    "m","n",
                                                        "p","q",    "r","s","t",
                                                    "u","v","w",    "x","y"
                                                  };
        /// <summary>
        /// 生成验证码所使用的随机数发生器
        /// </summary>
        private static Random verifycodeRandom = new Random();

        /// <summary>
        /// 禁用文字正则式对象
        /// </summary>
        private static Regex r_word;


        private static RegexOptions options = RegexOptions.IgnoreCase;

        public static Regex[] r = new Regex[4];

        static FrameWorkUtil()
        {
            r[0] = new Regex(@"(\r\n)", options);
            r[1] = new Regex(@"(\n)", options);
            r[2] = new Regex(@"(\r)", options);
            r[3] = new Regex(@"(<br />)", options);
        }

        /// <summary>
        /// 返回用户密码cookie明文
        /// </summary>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string GetCookiePassword(string key)
        {
            return DES.Decode(GetCookie("password"), key).Trim();
        }

        /// <summary>
        /// 返回用户密码cookie明文
        /// </summary>
        /// <param name="password">密码密文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string GetCookiePassword(string password, string key)
        {
            return DES.Decode(password, key);
        }


        /// <summary>
        /// 返回密码密文
        /// </summary>
        /// <param name="password">密码明文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string SetCookiePassword(string password, string key)
        {
            return DES.Encode(password, key);
        }


        /// <summary>
        /// 返回用户安全问题答案的存储数据
        /// </summary>
        /// <param name="questionid">问题id</param>
        /// <param name="answer">答案</param>
        /// <returns></returns>
        public static string GetUserSecques(int questionid, string answer)
        {
            if (questionid > 0)
                return Utils.MD5(answer + Utils.MD5(questionid.ToString())).Substring(15, 8);

            return "";
        }

        #region Cookies
        /// <summary>
        /// 写入用户cookie
        /// </summary>
        /// <param name="uInfo"></param>
        public static void WriteDYJUserCookies(UserInfo uInfo)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["dyj"];
            if (cookie == null) cookie = new HttpCookie("dyj");
            cookie.Values["password"] = Utils.UrlEncode(FrameWorkUtil.SetCookiePassword(uInfo.pass, GeneralConfigs.GetConfig().Passwordkey));
            cookie.Values["userid"] = uInfo.id.ToString();
            cookie.Values["userrname"] = Utils.UrlEncode(uInfo.rname.ToString());
            cookie.Values["username"] = uInfo.lname.ToString();
            cookie.Values["usergid"] = uInfo.gid.ToString();
            cookie.Values["usercid"] = uInfo.cid.ToString();
            cookie.Values["vercode"] = uInfo.olcode.ToString();
            cookie.Expires = DateTime.Now.AddMinutes(60);
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">项</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["dyj"];
            if (cookie == null)
            {
                cookie = new HttpCookie("dyj");
                cookie.Values[strName] = Utils.UrlEncode(strValue);
            }
            else
            {
                cookie.Values[strName] = Utils.UrlEncode(strValue);
                if (HttpContext.Current.Request.Cookies["dyj"]["expires"] != null)
                {
                    int expires = Utils.StrToInt(HttpContext.Current.Request.Cookies["dyj"]["expires"].ToString(), 0);
                    if (expires > 0)
                    {
                        cookie.Expires = DateTime.Now.AddMinutes(Utils.StrToInt(HttpContext.Current.Request.Cookies["dyj"]["expires"].ToString(), 0));
                    }
                }
            }

            string cookieDomain = GeneralConfigs.GetConfig().CookieDomain.Trim();
            if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain.TrimStart('.')) > -1 && IsValidDomain(HttpContext.Current.Request.Url.Host))
                cookie.Domain = cookieDomain;

            HttpContext.Current.Response.AppendCookie(cookie);
        }


        /// <summary>
        /// 写登录用户的cookie
        /// </summary>
        /// <param name="uid">用户Id</param>
        /// <param name="expires">cookie有效期</param>
        /// <param name="passwordkey">用户密码Key</param>
        /// <param name="templateid">用户当前要使用的界面风格</param>
        /// <param name="invisible">用户当前的登录模式(正常或隐身)</param>
        public static void WriteUserCookie(int uid, int expires, string username)
        {
            //UserInfo userinfo = LTJ.Data.DataProvider.UserInfo.GetUserInfo(uid);
            WriteUserCookie(uid, username, expires);
        }

        /// <summary>
        /// 写登录用户的cookie
        /// </summary>
        /// <param name="userinfo">用户信息</param>
        /// <param name="expires">cookie有效期</param>
        /// <param name="passwordkey">用户密码Key</param>
        /// <param name="templateid">用户当前要使用的界面风格</param>
        /// <param name="invisible">用户当前的登录模式(正常或隐身)</param>
        //public static void WriteUserCookie(UserInfo userinfo, int expires, string passwordkey)
        //{
        //    if (userinfo == null)
        //        return;

        //    HttpCookie cookie = new HttpCookie("ltj");
        //    cookie.Values["userid"] = userinfo.id.ToString();
        //    cookie.Values["username"] = userinfo.nickname.ToString();
        //    cookie.Values["password"] = Utils.UrlEncode(SetCookiePassword(userinfo.regpass, passwordkey));

        //    cookie.Values["referer"] = "index.aspx";
        //    cookie.Values["expires"] = expires.ToString();
        //    if (expires > 0)
        //    {
        //        cookie.Expires = DateTime.Now.AddMinutes(expires);
        //    }
        //    string cookieDomain = GeneralConfigs.GetConfig().CookieDomain.Trim();
        //    if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain.TrimStart('.')) > -1 && IsValidDomain(HttpContext.Current.Request.Url.Host))
        //    {
        //        cookie.Domain = cookieDomain;
        //    }

        //    HttpContext.Current.Response.AppendCookie(cookie);
        //}

        public static void WriteUserCookie(int uid, string username, int expires)
        {
            HttpCookie cookie = new HttpCookie("dyj");
            cookie.Values["userid"] = uid.ToString();
            cookie.Values["username"] =Utils.UrlEncode(username.ToString());
            cookie.Values["expires"] = expires.ToString();
            if (expires > 0)
            {
                cookie.Expires = DateTime.Now.AddMinutes(expires);
            }
            string cookieDomain = GeneralConfigs.GetConfig().CookieDomain.Trim();
            if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain.TrimStart('.')) > -1 && IsValidDomain(HttpContext.Current.Request.Url.Host))
            {
                cookie.Domain = cookieDomain;
            }

            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 获得cookie值
        /// </summary>
        /// <param name="strName">项</param>
        /// <returns>值</returns>
        public static string GetCookie(string strName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies["dyj"] != null && HttpContext.Current.Request.Cookies["dyj"][strName] != null)
                return Utils.UrlDecode(HttpContext.Current.Request.Cookies["dyj"][strName].ToString());

            return "";
        }


        /// <summary>
        /// 清除登录用户的cookie
        /// </summary>
        public static void ClearUserCookie()
        {
            ClearUserCookie("dyj");
        }

        public static void ClearUserCookie(string cookieName)
        {
            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Values.Clear();
            cookie.Expires = DateTime.Now.AddYears(-1);
            string cookieDomain = GeneralConfigs.GetConfig().CookieDomain.Trim();
            if (cookieDomain != string.Empty && HttpContext.Current.Request.Url.Host.IndexOf(cookieDomain.TrimStart('.')) > -1 && IsValidDomain(HttpContext.Current.Request.Url.Host))
                cookie.Domain = cookieDomain;
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        #endregion

        /// <summary>
        /// 产生验证码
        /// </summary>
        /// <param name="len">长度</param>
        /// <returns>验证码</returns>
        public static string CreateAuthStr(int len)
        {
            int number;
            StringBuilder checkCode = new StringBuilder();
            Random random = new Random();

            for (int i = 0; i < len; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    checkCode.Append((char)('0' + (char)(number % 10)));
                else
                    checkCode.Append((char)('A' + (char)(number % 26)));
            }
            return checkCode.ToString();
        }

        /// <summary>
        /// 产生验证码
        /// </summary>
        /// <param name="len">长度</param>
        /// <param name="OnlyNum">是否仅为数字</param>
        /// <returns>string</returns>
        public static string CreateAuthStr(int len, bool OnlyNum)
        {
            int number;
            StringBuilder checkCode = new StringBuilder();

            for (int i = 0; i < len; i++)
            {
                if (!OnlyNum)
                    number = verifycodeRandom.Next(0, verifycodeRange.Length);
                else
                    number = verifycodeRandom.Next(0, 10);

                checkCode.Append(verifycodeRange[number]);
            }
            return checkCode.ToString();
        }

        /// <summary>
        /// 是否为有效域
        /// </summary>
        /// <param name="host">域名</param>
        /// <returns></returns>
        public static bool IsValidDomain(string host)
        {
            if (host.IndexOf(".") == -1)
                return false;

            return new Regex(@"^\d+$").IsMatch(host.Replace(".", string.Empty)) ? false : true;
        }

        /// <summary>
        /// 错误展示
        /// </summary>
        /// <param name="errormsg">错误信息</param>
        /// <param name="url">返回链接</param>
        /// <param name="isreturn">是否返回</param>
        public static void ShowError(string errormsg, string url, bool isreturn)
        {
            ShowMSG(errormsg, MsgType.ErrorMsg, url, isreturn);
        }

        public static void ShowRight(string rightmsg, string url, bool isreturn)
        {
            ShowMSG(rightmsg, MsgType.RightMsg, url, isreturn);
        }

        internal static void ShowMSG(string msg, MsgType mtype, string url, bool isreturn)
        {
            string mtitle = "";
            string mimg = "";

            switch (mtype)
            {
                case MsgType.ErrorMsg:
                    mtitle = "错误提示";
                    mimg = "/images/error.gif";
                    break;
                case MsgType.RightMsg:
                    mtitle = "页面提示";
                    mimg = "/images/right.gif";
                    break;
                default:
                    mtitle = "页面提示";
                    mimg = "/images/right.gif";
                    break;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
            sb.Append("<head>\r\n");
            sb.Append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n");
            sb.Append("<title>提示页</title>\r\n");
            sb.Append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=7\" />\r\n");
            sb.Append("<link href=\"/css/comm.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n");
            sb.Append("<link href=\"/css/main.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n");
            sb.Append("</head>\r\n");
            sb.AppendFormat("<body {0}>\r\n", isreturn ? "onload=\"returnPage('" + url + "');\"" : "");
            sb.Append("<div class=\"cot\">\r\n");
            sb.Append("<div class=\"erw\">\r\n");
            sb.AppendFormat("<span><img alt=\"{0}\" src=\"{1}\" /></span>\r\n", mtitle, mimg);
            sb.AppendFormat("<strong>{0}</strong>\r\n", mtitle);
            sb.AppendFormat("<p class=\"mar_top\">{0}</p>\r\n", msg);
            sb.Append("</div>\r\n");
            sb.Append("</div>\r\n");
            sb.Append("</body>\r\n");
            sb.Append("<script>var intLeft = 2; function returnPage(Url){if (0 == intLeft) top.location.href=Url;else {intLeft -= 1;setTimeout(\"returnPage('\"+Url+\"')\", 2000);}}</script>\r\n");
            sb.Append("</html>");

            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Write(sb.ToString());
            System.Web.HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 保存企业Logo
        /// </summary>
        /// <param name="MaxAllowFileSize">最大允许的头像文件尺寸(单位:KB)</param>
        /// <returns>保存文件的相对路径</returns>
        public static string SaveCorpLogo(int corpid)
        {
            string filename = Path.GetFileName(HttpContext.Current.Request.Files[0].FileName);
            string fileextname = Path.GetExtension(filename).ToLower();
            string filetype = HttpContext.Current.Request.Files[0].ContentType.ToLower();

            // 判断 文件扩展名/文件大小/文件类型 是否符合要求
            if (Utils.InArray(fileextname, ".jpg,.gif,.png") && filetype.StartsWith("image"))
            {
                StringBuilder savedir = new StringBuilder(BaseConfigs.GetSitePath + "upload/");

                int t1 = (int)((double)corpid / (double)10000);
                savedir.Append(t1);
                savedir.Append("/");
                int t2 = (int)((double)corpid / (double)200);
                savedir.Append(t2);
                savedir.Append("/");
                if (!Directory.Exists(Utils.GetMapPath(savedir.ToString())))
                    Utils.CreateDir(Utils.GetMapPath(savedir.ToString()));

                string newfilename = savedir.ToString() + corpid.ToString() + fileextname;
                File.Delete(Utils.GetMapPath(savedir.ToString()) + corpid.ToString() + ".jpg");
                File.Delete(Utils.GetMapPath(savedir.ToString()) + corpid.ToString() + ".gif");
                File.Delete(Utils.GetMapPath(savedir.ToString()) + corpid.ToString() + ".png");
                HttpContext.Current.Request.Files[0].SaveAs(Utils.GetMapPath(newfilename));
                return newfilename;

            }
            return "";
        }

        /// <summary>
        /// 判断是否有上传的文件
        /// </summary>
        /// <returns>是否有上传的文件</returns>
        public static bool IsPostFile()
        {
            for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
            {
                if (HttpContext.Current.Request.Files[i].FileName != "")
                    return true;
            }
            return false;
        }
    }
}
